package com.cnap.multiclouldmgmt.model.flavor;

import com.cnap.multiclouldmgmt.service.impl.ScalingServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 实例规格信息
 * 
 * @author tyj
 * @date 2022/11/17
 */
public class FlavorInfo implements Serializable {

    private static final Logger LOGGER = LoggerFactory.getLogger(FlavorInfo.class);


    private static final long serialVersionUID = -2006104874416689043L;

    /**
     * 实例规格云商ID
     */
    private String flavorId;
    /**
     * 实例规格描述
     */
    private String describe;

    private int cpu;

    private int mem;

    public int getCpu() {

        if (cpu == 0){
            handdleCpuAndMem();
        }


        return cpu;
    }

    public void setCpu(int cpu) {
        this.cpu = cpu;
    }

    public int getMem() {

        if (mem == 0){
            handdleCpuAndMem();
        }

        return mem;
    }

    public void setMem(int mem) {
        this.mem = mem;
    }

    public FlavorInfo() {
        // 默认构造方法
    }


    public FlavorInfo(String flavorId, String describe) {
        this.flavorId = flavorId;
        this.describe = describe;
    }

    public String getFlavorId() {
        return flavorId;
    }

    public void setFlavorId(String flavorId) {
        this.flavorId = flavorId;
    }

    public String getDescribe() {
        return describe;
    }

    public void setDescribe(String describe) {
        this.describe = describe;
    }

    //解析出cpu和mem大小，格式长这样c7.xlarge.2[4Cores][8GB]
    private void handdleCpuAndMem(){
        try {
            String cpuAndMem =
                    describe
                            .replace(flavorId, "")
                            .replace(".0", "");
            String[] nums = cpuAndMem.split("ores");
            String regEx = "[^0-9]";
            Pattern p = Pattern.compile(regEx);
            //正则表达式获取数字
            for (String num : nums) {
                Matcher m = p.matcher(num);

                if (cpu == 0) {
                    cpu = Integer.parseInt(m.replaceAll("").trim());
                    continue;
                }

                mem = Integer.parseInt(m.replaceAll("").trim());
            }
        }catch (Exception e){

            LOGGER.error("handle flavorInfo fail id={} describe={}",flavorId,describe);
        }
    }
}
